import os
import pika
from dotenv import load_dotenv

load_dotenv()


class RabbitMQConsumer:
    def __init__(self, queue_name):
        self.HOST = os.getenv('RABBIT_MQ_HOST')
        self.PORT = os.getenv('RABBIT_MQ_PORT')
        self.USERNAME = os.getenv('RABBIT_MQ_USERNAME')
        self.PASSWORD = os.getenv('RABBIT_MQ_PASSWORD')
        self.VIRTUAL_HOST = os.getenv('RABBIT_MQ_VIRTUAL_HOST')
        self.queue_name = queue_name

        self._connect_and_consume()

    def _connect_and_consume(self):
        """内部方法：建立连接并开始消费消息"""
        connection_params = pika.ConnectionParameters(
            host=self.HOST,
            port=self.PORT,
            virtual_host=self.VIRTUAL_HOST,
            credentials=pika.PlainCredentials(self.USERNAME, self.PASSWORD)
        )
        self.connection = pika.BlockingConnection(connection_params)
        self.channel = self.connection.channel()

        # 声明队列，确保队列存在]
        print(self.queue_name)
        self.channel.queue_declare(queue=self.queue_name)

        # 定义回调函数处理接收到的消息
        def callback(ch, method, properties, body):
            print(" [x] Received %r" % body)

        # 开始消费
        self.channel.basic_consume(queue=self.queue_name, on_message_callback=callback, auto_ack=True)

        print(' [*] Waiting for messages. To exit press CTRL+C')
        self.channel.start_consuming()


# 使用示例
if __name__ == "__main__":
    QUEUE_NAME = os.getenv('RABBIT_MQ_QUEUE_NAME')
    consumer = RabbitMQConsumer(QUEUE_NAME)
